/*
 * (C) Copyright 2006-2010 Nuxeo SAS (http://nuxeo.com/) and contributors.
 *
 * All rights reserved. This program and the accompanying materials
 * are made available under the terms of the GNU Lesser General Public License
 * (LGPL) version 2.1 which accompanies this distribution, and is available at
 * http://www.gnu.org/licenses/lgpl.html
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
 * Lesser General Public License for more details.
 *
 * Contributors:
 *     bstefanescu
 */
package org.nuxeo.gwt.habyt.invocation.client;

import com.google.gwt.dom.client.Element;
import com.google.gwt.user.client.ui.DisclosurePanel;
import com.google.gwt.user.client.ui.HTML;
import com.google.gwt.user.client.ui.SimplePanel;

/**
 * Widget that can be used for development messages in widget bindings.
 * 
 * Instead of displaying an Window alert wit some message or stack trace you can
 * return this widget from a binding when XHTML input is not OK.
 * 
 * @author <a href="mailto:bs@nuxeo.com">Bogdan Stefanescu</a>
 * 
 */
public class ErrorWidget extends SimplePanel {

    protected Element element;

    public ErrorWidget(String message) {
        this(message, null);
    }

    public ErrorWidget(String message, Throwable cause) {
        DisclosurePanel panel = new DisclosurePanel();
        HTML header = new HTML("<h3 style=\"color:red\">Error: " + message
                + "</h3>");
        panel.setHeader(header);
        panel.setOpen(false);
        if (cause == null) {
            cause = new Throwable("Stack Trace:");
        }
        String details = "<pre style=\"color:red;border: 1px solid gray;\" >"
                + cause.getMessage() + "\n\n" + getStackTrace(cause) + "</pre>";
        panel.setContent(new HTML(details));
        setWidget(panel);
    }

    public static String getStackTrace(Throwable e) {
        Object[] stackTrace = e.getStackTrace();
        String output = "";
        for (Object line : stackTrace) {
            output += line + "\n";
        }
        return output;
    }

}
